"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/5/30 10:01
@Description : 
使用文件持久化的方式，改写之前编写的学生信息管理系统（面向对象的思路）
"""
import json


class Student:
    def __init__(self, sno, name, age, sex):
        self.__sno = sno
        self.__name = name
        self.__age = age
        self.__sex = sex

    # 查询学生信息列表
    @staticmethod
    def student_list(filename):
        with open(filename, 'r', encoding='utf-8') as f:
            file_students = json.load(f)
            student_lst = file_students['students']
        return student_lst

    # 根据学号查询学生信息
    @staticmethod
    def student_one(filename, stu_no):
        with open(filename, 'r', encoding='utf-8') as f:
            file_students = json.load(f)
            student_lst = file_students['students']
            for student in student_lst:
                if student['sno'] == stu_no:
                    break
            else:
                return None
            return student

    # 修改学生信息
    @staticmethod
    def student_update(filename, student_update):
        update_keys = student_update.keys()
        with open(filename, 'r', encoding='utf-8') as f:
            students = json.load(f)['students']
            print(students)
            for student in students:
                if student['sno'] == student_update['sno']:
                    if 'name' in update_keys:
                        student['name'] = student_update['name']
                    if 'age' in update_keys:
                        student['age'] = student_update['age']
                    if 'sex' in update_keys:
                        student['sex'] = student_update['sex']
                    break
            else:
                raise Exception('学号不存在')
            with open(filename, 'w', encoding='utf-8') as f:
                student_json = json.dumps({'students': students}, ensure_ascii=False, indent=2)
                f.write(student_json)

    # 删除学生信息
    @staticmethod
    def student_delete(filename, stu_no):
        with open(filename, 'r+', encoding='utf-8') as f:
            students = json.load(f)['students']
            for student in students:
                if student['sno'] == stu_no:
                    students.remove(student)
                    break
            else:
                raise Exception('删除的学生不存在')
        with open(filename, 'w', encoding='utf-8') as f:
            student_json = json.dumps({'students': students}, ensure_ascii=False, indent=2)
            f.write(student_json)

    # 新增学生信息
    @staticmethod
    def student_insert(filename, student):
        with open(filename, 'r', encoding='utf-8') as f:
            students = json.load(f)['students']
            students.append(student)

        with open(filename, 'w', encoding='utf-8') as f:
            student_json = json.dumps({'students': students}, ensure_ascii=False, indent=2)
            f.write(student_json)


# 导入 prettytable模块
from prettytable import PrettyTable

# 设置欢迎词
welcome_info = """
******************欢迎使用学生信息管理系统********************
    1. 查看学生列表
    2. 查询学生信息
    3. 新增学生信息
    4. 修改学生信息
    5. 删除学生信息
    6. 退出系统
************************************************************
"""

# 定义容器存储数据
students_list = []

# 创建一个表格
table = PrettyTable(['学号', '姓名', '性别', '年龄'])
# 设置最小列宽
table.min_width = 10
while True:
    print(welcome_info)
    # 接收用户选择的功能选项
    user_choice = input('请输入功能序号:')
    # 判定用户的选择  进入不同的功能区  分支 match
    match user_choice:
        case '1':
            print('>' * 20, '查看学生列表', '<' * 20)
            # 判定容器中是否有学生信息
            result = Student.student_list('students.json')
            if result:
                # 遍历学生列表容器
                for student in result:
                    # 添加数据行
                    table.add_row([student.get('sno'), student.get('name'), student.get('sex'), student.get('age')])
                # 打印表格
                print(table)
                # 清空表格的数据行
                table.clear_rows()
            else:
                print('没有学生信息,请添加后查看')
        case '2':
            print('>' * 20, '查询学生信息', '<' * 20)
            # 提示用户输入学号
            sno = input('请输入学号:')
            # 遍历列表  判定学号在列表中的哪个字典中 sno
            student_one = Student.student_one('students.json', sno)
            if student_one:
                table.add_row(
                    [student_one.get('sno'), student_one.get('name'), student_one.get('sex'), student_one.get('age')])
                print(table)
                table.clear_rows()
            else:
                print('查询的学生信息不存在!!!')
        case '3':
            print('>' * 20, '新增学生信息', '<' * 20)
            # 保证的学号的唯一性
            while True:
                sno = input('请输入学号:')
                # 遍历学生信息列表  判定学号是否存在
                student_result = Student.student_list('students.json')
                for student in student_result:
                    if student.get('sno') == sno:
                        print('学号已存在，请重新输入')
                        break
                else:
                    name = input('请输入名字:')
                    age = int(input('请输入年龄:'))
                    sex = input('请输入性别:')
                    # 将用户输入的信息存储在字典中  添加到list中
                    user_input_student = {
                        'sno': sno,
                        'name': name,
                        'age': age,
                        'sex': sex
                    }
                    Student.student_insert('students.json', user_input_student)
                    is_continue = input("是否继续录入【y/n】:")
                    if is_continue == 'n':
                        break
            print('学生信息添加成功!!!')
        case '4':
            print('>' * 20, '修改学生信息', '<' * 20)
            student_update = {}
            stu_no = input('请输入学号:')
            student_update['sno'] = stu_no
            #  进入修改阶段
            update_name = input('修改名字【y/n】:')
            if update_name == 'y':
                name = input('请输入名字:')
                student_update['name'] = name
            update_age = input('修改年龄【y/n】:')
            if update_age == 'y':
                age = int(input('请输入年龄:'))
                student_update['age'] = age
            update_sex = input('修改性别【y/n】:')
            if update_sex == 'y':
                sex = input('请输入性别:')
                student_update['sex'] = sex
            try:
                Student.student_update('students.json', student_update)
            except Exception as e:
                print(e)
                print('修改失败!!!')
            else:
                print('修改成功')
        case '5':
            print('>' * 20, '删除学生信息', '<' * 20)
            sno = input('请输入学号:')
            try:
                Student.student_delete('students.json', sno)
            except Exception as e:
                print(e)
                print('删除失败,学号不存在!!!')
        case '6':
            print('>' * 20, '退出系统', '<' * 20)
            break
        case _:
            print('请输入正确的功能序号!!!')

    # 询问用户是否退出
    is_exit = input('是否退出系统【y/n】：')
    if is_exit == 'y':
        break
print('------程序退出,欢迎下次使用-------')
